package cn.xxm.scene.validate.processor;




import cn.xxm.scene.validate.annotation.VLength;
import cn.xxm.scene.validate.exception.ValidateException;
import cn.xxm.scene.validate.response.ResponseInfo;

import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;

@SuppressWarnings("rawtypes")
public class LengthProcessor extends ValidateProcessor {
	private int min;
	private int max;
	private boolean byteUnit = false;//是否以字节计算长度
	private String charset;
	
	@SuppressWarnings("unchecked")
	public LengthProcessor(VLength vLength){
		Class<Enum> enumClass = (Class<Enum>)vLength.enumClass();
		Enum enumInstance = Enum.valueOf(enumClass, vLength.enumName());
		if(! (enumInstance instanceof ResponseInfo)) {//枚举类型没实现ResponseInfo则抛异常
			throw new ValidateException("枚举类型<"+enumClass+">未实现接口<"+ResponseInfo.class+">")  ;
		}
		super.setResponseInfo(enumInstance);
		min = vLength.min();
		max = vLength.max();
		byteUnit = vLength.byteUnit();
		charset = vLength.charset();
		if(charset.length() == 0){
			charset = Charset.defaultCharset().name();
		}
	}
	
	@Override
	public boolean validate(Object value){
		if(value == null){
			return false;
		}
		String str = value.toString();
		int length = 0;
		if(byteUnit){
			try {
				length = str.getBytes(charset).length;
			} catch (UnsupportedEncodingException e) {
				logger.info("字符串长度校验，未支持的字符集{}",charset);
				length = str.getBytes().length;
			}
		} else {
			length = str.length();
		}
		if(min >= 0 && length < min){
			return false;
		}
		if(max >= 0 && length > max){
			return false;
		}
		return true;
	}
	
}
